require 'rubygems'
require 'gruff'
require "report/Report"
require "report/Section"

class AverageDurationPerCorrectCharacterPerPhraseBySet
  NAME = "Average Duration Between 2 Correct Characters (Group by Subject)"
  
  def initialize
    @order = {
      2 => [1, 2, 3, 4, 5, 6, 7, 8],
      3 => [1, 2, 3, 4, 5, 6, 7, 8],
      4 => [8, 7, 6, 5, 4, 3, 2, 1],
      5 => [1, 2, 8, 7, 3, 4, 6, 5],
      6 => [3, 4, 7, 2, 5, 6, 7, 8],  
    }
  end
  
  
  def analyze(directory, experimentalData, phraseCards)
    
    #override the filter
    experimentalData.layer1filter = Hash.new([])
    experimentalData.getData
    
    #get the data
    data = experimentalData.group_by_uid

    data.each_pair do |uid, entries|

      all_data = []
            
      #create the report
      report = Report.new(directory, "Subject_#{uid}")
      
      data_by_set = {}

      entries.each do |e|
        #initialize if nil
        data_by_set[e.set] ||= []
        data_by_set[e.set] << e
      end



      #do some simple statistics
      stat = ""

      #average value of each set
      avg_durations_of_sets = {}

      #Generate a section for each set
      @order[uid].each do |i|
        #create a graph for each set
        g = create_graph(i)
           
        entries =  data_by_set[i]
        entries.sort! { |x,y| x.date <=> y.date }
          
        avg_durations = entries.collect do |e|
          _get_avg_duration(e)
        end
        all_data.concat avg_durations
        
        g.data "Subject:#{uid} Set:#{i}", avg_durations
        
        avg = avg_durations.inject{ |sum, el| sum + el }.to_f / avg_durations.length
        stat = "<b>Average: </b> #{avg} <br/>"          
        report.new_section("Set #{i}", stat, g)
      end  
       
      g = create_graph("ALL")
      g.data "Subject:#{uid} All set", all_data

      avg = all_data.inject{ |sum, el| sum + el }.to_f / all_data.length
      stat = "<b>Average: </b> #{avg} <br/>"          
      report.new_section("ALL Set", stat, g)
      
       
      #generate report
      report.to_html
    end    
    
  end

  #  S  t  u  s  bs   d  e  n  t
  #   t1 t2 D  D   t5  t6 t7 t8
  def _get_avg_duration(e)
    #marks the time duratin the have to be deleted
    marks = []
    e.sequence.each do |seq|
      marks << 0
      if ( seq[0].eql?("\b"))
        marks[-2] = 1 unless marks[-2] == nil
        marks[-3] = 1 unless marks[-3] == nil
      end
    end

    durations = []
    marks[-1] = 1 # remove the last one which is always zero
    marks.length.times do |i|
      durations << e.sequence[i][1] unless marks[i]==1
    end

    return durations.inject{ |sum, el| sum + el }.to_f / durations.length
  end

  def create_graph (set)
    g = Gruff::Line.new
    g.dot_radius = 2
    g.line_width = 2
    g.x_axis_label = "Phrases"
    g.y_axis_label = "Time (10 ms)"
    g.title = "Avg Duration Between Characters(Set:#{set})"
    g
  end
end